
var cheerio = require('cheerio');

var requestBase = require('../common/request-base');

module.exports = {
  show: show,
  postData: postData
};

var url = 'http://php.weather.sina.com.cn/flight/';


function show(req, res, next) {
  var resData = {
    isQuery: true,
    searchType: 'news'
  };
  res.render('query', resData);
}


function postData(req, res, next) {

  var fno = req.body.fno;
  var fromCityName = req.body.fromCityName;
  var toCityName = req.body.toCityName;

  var postData = {
    fromCityName: fromCityName ? fromCityName : '',
    fromCityCode: '',
    toCityName: toCityName ? toCityName : '',
    toCityCode: '',
    Airlines: '',
    'button.x': '',
    'button.y': '',
    fno: fno ? fno : ''
  };

  var $ = {};

  requestBase.postBufferData({encoding: null, url: url, formData: postData}, 'GBK')

    .then(function(data) {
      $ = cheerio.load(data, {decodeEntities: false});
    })

    .then(function() {
      var $tbody = $('#hover_tb tbody');
      $tbody.find('tr').each(function() {
        $(this).find('td').eq(9).remove();
      });
      return $tbody.html();
    })

    .then(function(resData) {
      res.send(resData);
    })

    .catch(function(err) {
      console.log(err);
    });

}